<template>
  <div class="bigbox">
    <!-- 左侧盒子树结构 -->
    <div class="leftbox">
      <div class="title">
        <template>
          <el-input
            class="inline-input"
            v-model="filterText"
            size="small"
            style="margin-bottom: 10px; width: 100%"
            placeholder="输入关键字搜索"
          ></el-input>
        </template>
        <span><button @click="addtianjia">添加</button></span>
      </div>
      <div class="treebox">
        <!-- 树状图区域结构 -->
        <el-tree
          :data="treeList"
          :props="props"
          show-checkbox
           node-key="id"
          @check="handleCheckChange"
          :filter-node-method="filterNode"
          :highlight-current="true"
          @node-click="handleNodeClick"
          ref="tree"
        >
          <!-- <template slot-scope="{ node, data }">
            <span :style="{ fontSize: '14px', color: '#606266' }">
              <img
                :src="'data:image/png;base64,' + data.iconBase64"
                style="
                  width: 16px;
                  height: 16px;
                  margin-right: 5px;
                  vertical-align: bottom;
                "
              />
              {{ node.label }}</span
            >
          </template> -->
        </el-tree>
      </div>
    </div>
    <!-- 右侧盒子主体 -->
    <div class="rightbox">
      <!-- 导航栏 -->
      <div class="righttopbox">
        <div>
          <el-radio-group v-model="radio" style="margin-right: 20px">
            <el-radio-button label="日"></el-radio-button>
            <el-radio-button label="月"></el-radio-button>
            <el-radio-button label="年"></el-radio-button>
          </el-radio-group>
          <el-date-picker
            style="width: 200px; height: 40px; line-height: 40px"
            v-model="date"
            :type="radio == '日' ? 'date' : radio == '月' ? 'month' : 'year'"
            :format="
              radio == '日' ? 'yyyy-MM-dd' : radio == '月' ? 'yyyy-MM' : 'yyyy'
            "
            placeholder="选择时间"
          >
          </el-date-picker>
        </div>
        <div>
          <button class="chongzhi" @click="chongzhi">重置</button>
          <button class="button" @click="submit">查询</button>
        </div>
      </div>
      <!-- echart/table页 -->
      <div class="rightbodybox">
        <div class="tages">
          <!-- <el-tag
            v-for="tag in tags"
            :key="tag.name"
            type=""
            @close="handleClose(tag)"
            :closable="true"
          >
            {{ tag.name }}</el-tag
          > -->
        </div>
        <div class="title">
          <div>
            <div v-show="isshow == 'table'">
              <img
                src="@/assets/energy-consumption/Basic-analysis/icon/tongji.png"
                alt=""
              />
              <span>统计表</span>
            </div>
            <div v-show="isshow == 'echart' && shouech">
              <img
                src="@/assets/energy-consumption/Basic-analysis/echfyhe.png"
                alt=""
              />
              <span>负荷</span>
            </div>
          </div>
          <div>
            <span><button class="button" @click="exporttab">导出</button></span>
            <span>
              <i
                @click="isshow = 'echart'"
                :style="{ color: isshow === 'echart' ? '#007cee' : '#000' }"
                class="iconfont icon-zhuzhuangtutubiao"
              ></i>
              <i
                @click="isshow = 'table'"
                :style="{ color: isshow === 'table' ? '#007cee' : '' }"
                class="iconfont icon-biaoge"
              ></i>
            </span>
          </div>
        </div>
        <div class="tablebox">
          <!-- 表格盒子 -->
          <div v-show="isshow == 'table'" class="fartab">
            <el-table
              v-loading="loading"
              :data="tableData"
              style="width: 100%"
              border
              height="100%"
              ref="table"
              :header-cell-style="{
                background: '#f5f5f5',
                'text-align': 'center',
              }"
              :row-style="{
                'max-height': '40px',
              }"
            >
              <el-table-column
                type="index"
                align="center"
                label="序号"
                width="100px"
              >
              </el-table-column>
              <el-table-column
                prop="companyName"
                label="企业"
                min-width="300px"
              >
              </el-table-column>
              <el-table-column
                prop="timeReading"
                align="center"
                label="日期"
                min-width="150px"
              >
              </el-table-column>
              <el-table-column
                v-for="(item, index) in tags"
                :key="index"
                :label="item.name"
                min-width="200px"
              >
                <el-table-column
                  align="right"
                  prop="usageValue"
                  label="用电量(kWh)"
                  min-width="100px"
                >
                  <template slot-scope="scope">
                    {{
                      scope.row.departmentEnergyList[index]?.usageValue || ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="right"
                  prop="loadValue"
                  label="负荷(kW)"
                  min-width="100px"
                >
                  <template slot-scope="scope">
                    {{ scope.row.departmentEnergyList[index]?.loadValue || "" }}
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
            <!-- 底部分页 -->
          </div>
          <div class="keshihua" v-show="isshow == 'echart'">
            <div
              v-loading="loading1"
              v-if="shouech"
              class="fuherchart"
              id="loadecharts"
            ></div>
            <div>
              <img
                style="vertical-align: middle; margin-right: 10px"
                src="../../../../assets/energy-consumption/Basic-analysis/dianliang.png"
                alt=""
              />
              <span>用量</span>
            </div>
            <div
              v-loading="loading2"
              class="dianliangechart"
              id="usageecharts"
            ></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { exportexcel } from '@/utils/excel'
import {
  getDepartmentTreeApi,
  getEnergyListApi,
  getLoadLineListApi,
  getUsageLineListApi
} from '@/api/energy-consumption/Department/Query'
import dayjs from 'dayjs'
export default {
  name: 'DepartmentQuery',
  data () {
    return {
      treeList: [],
      loading: false,
      loading1: false,
      loading2: false,
      shouech: true,
      isshow: 'echart',
      date: null,
      value1: '',
      value3: '',
      value2: '',
      radio: '日',
      filterText: '',
      props: {
        label: 'name',
        children: 'sonList'
      },
      loadList: [],
      usageList: [],
      array: [],
      options: [],
      model: '',
      tableData: [],
      tableConfig: [],
      tags: [],
      treevalue: {},
      pageobj: {
        pageNo: 0,
        pageSize: 15
      },
      totalCount: '',
      companyName: ''
    }
  },

  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    },
    radio: {
      handler (newValue) {
        if (this.radio == '日') {
          this.date = dayjs().format('YYYY-MM-DD')
        } else if (this.radio == '月') {
          this.date = dayjs().format('YYYY-MM')
        } else if (this.radio == '年') {
          this.date = dayjs().format('YYYY')
        }
      },
      immediate: true
    }
  },
  async mounted () {
    this.getDepartmentTree()
    this.myChart1([])
    this.myChart2([])
  },
  methods: {

    // 树结构列表
    async getDepartmentTree () {
      const res = await getDepartmentTreeApi()
      this.treeList = res.data.list
    },

    // 查询按钮
    async submit () {
      if (this.tags.length == 0) return this.$message.warning('请先选择设备')
      // 判断类型是否为电 如果是调负荷接口生成负荷图表 如果不是就只调用量和表格的数据
      // if (this.model == '01') {
      //   this.shouech = true
      //   this.getLoadLineList().then((list) => {
      //     this.myChart1(list)
      //   })
      // } else {
      //   this.shouech = false
      // }
      // this.getUsageLineList().then((list) => {
      //   this.$message.success('获取数据成功')
      //   this.myChart2(list)
      // })
      await this.getdatalist()
      this.$forceUpdate()
    },

    // 获取负荷曲线数据
    async getLoadLineList () {
      this.loading1 = true
      const res = await getLoadLineListApi({
        contrastString: this.tags.map((i) => i.id).join(','),
        nameContrastString: this.tags.map((i) => i.name).join(','),
        dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
        dateString: this.date
      })
      this.loadList = res.data.list
      this.loading1 = false
    },
    // 获取用量曲线数据
    async getUsageLineList () {
      this.loading2 = true
      const res = await getUsageLineListApi({
        contrastString: this.tags.map((i) => i.id).join(','),
        nameContrastString: this.tags.map((i) => i.name).join(','),
        dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
        dateString: this.date
      })
      this.usageList = res.data.list
      this.loading2 = false
    },
    async getEnergyList () {
      const res = await getEnergyListApi({
        companyName: this.tags[0]?.parentName,
        contrastString: this.tags.map((i) => i.id).join(','),
        nameContrastString: this.tags.map((i) => i.name).join(','),
        dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
        dateString: this.date
      })
      this.tableData = res.data.list
    },

    // 导出
    exporttab () {
      if (this.tags.length == 0) return this.$message.warning('请先选择设备')
      // const arr = []
      // this.tags.filter((ele) => {
      //   return arr.push(ele.className + '_' + ele.id + '_' + ele.name)
      // })
      exportexcel(
        '/ecm-microservice-biz/ecm/department/energy/data/exportExcel',
        {
          contrastString: this.tags.map((i) => i.id).join(','),
          nameContrastString: this.tags.map((i) => i.name).join(','),
          dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
          dateString: this.date,
          companyName: this.tags[0]?.parentName
        },
        '部门能耗查询'
      )
    },
    // 树节点选中
    handleNodeClick (val, node) {
      if (node.level !== 2) return
      this.treevalue = val
      const node1 = this.$refs.tree.getNode(val)
      console.log(node1)
      console.log(this.treevalue)
    },
    handleCheckChange (checkedNodes, checkedNode) {
      console.log(checkedNodes, checkedNode)
      // if (this.tags.length > 0 && data.parentName !== this.tags[0].parentName) {
      //   return this.$message({
      //     message: '请选择同企业部门',
      //     type: 'warning',
      //     duration: 2000
      //   })
      // }
      if (this.tags.length > 0) {
        if (!checkedNodes?.parentName && checkedNodes?.parentName !== this.tags[0]?.parentName) {
          this.$refs.tree.setChecked(checkedNodes.id, false, true)
          this.$message({
            message: '请选择同企业部门',
            type: 'warning',
            duration: 2000
          })
        }
      }

      this.tags = this.$refs.tree.getCheckedNodes(false, true).filter(i => i.parentName)
      console.log(this.tags)
      if (this.tags.length > 0) {
        this.getdatalist()
      } else {
        this.myChart1([])
        this.myChart2([])
        this.tableData = []
      }

      // if (checked) {
      //   if (!this.tags.length > 0) {
      //     this.tags.push(data)
      //     return this.getdatalist()
      //   }
      //   if (data.parentName !== this.tags[0].parentName) {
      //     return this.$message({
      //       message: '请选择同企业部门',
      //       type: 'warning',
      //       duration: 2000
      //     })
      //   }
      // }
    },
    // 添加tags
    addtianjia () {
      // 判断当前是否有选中节点 不然不允许添加
      if (!this.treevalue.id) {
        return this.$message({
          type: 'warning',
          message: '请选择部门',
          duration: 2000
        })
      }
      console.log(this.treevalue)

      if (!this.tags.length > 0) {
        this.tags.push(this.treevalue)
        return this.getdatalist()
      }
      if (this.treevalue.parentName !== this.tags[0].parentName) {
        return this.$message({
          message: '请选择同企业部门',
          type: 'warning',
          duration: 2000
        })
      }
      if (this.tags.length >= 20) {
        return this.$message({
          message: '最多添加20个部门',
          type: 'warning',
          duration: 2000
        })
      }
      // 检查是否存在重复项
      const isDuplicate = this.tags.some((ele) => ele.id == this.treevalue.id)
      // 如果不存在重复项，则将节点添加到数组中并执行 this.submit 函数
      if (!isDuplicate) {
        this.tags.push(this.treevalue)
        this.getdatalist()
        // this.submit()
      } else {
        // 如果存在重复项，则弹出提示
        this.$message({
          message: '请勿重复添加',
          type: 'warning',
          duration: 2000
        })
      }
    },
    // 移除tags
    handleClose (val) {
      this.tags = this.tags.filter((ele) => ele.id !== val.id)
    },
    // 重置
    chongzhi () {
      this.radio = '日'
      this.tags = {}
      const tree = this.$refs.tree
      const nodes = tree.getCheckedNodes()
      nodes.forEach(node => {
        tree.setChecked(node, false)
      })
      this.myChart1([])
      this.myChart2([])
      this.tableData = []
      this.isshow = 'echart'
    },
    // 获取列表
    async getdatalist () {
      this.loading = true
      const promises = [
        this.getLoadLineList().then(() => this.myChart1(this.loadList)),
        this.getUsageLineList().then(() => this.myChart2(this.usageList)),
        this.getEnergyList().then(() => {
          this.loading = false
        })
      ]

      // 等待所有Promise完成
      await Promise.all(promises)
    },
    // 获取负荷图标
    myChart1 (list) {
      const myChart = echarts.init(document.getElementById('loadecharts'))
      const timePoints = list[0]?.datalist.map((ele) => ele.timeReading)
      const series = list.map((ele) => {
        return {
          name: ele.name,
          data: ele.datalist.map((ele) => ele.valueReading),
          type: 'line',
          smooth: true
        }
      })
      const option = {
        grid: {
          top: '10%',
          bottom: '7%',
          left: '5%',
          right: '0%'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {

        },
        xAxis: [
          {
            type: 'category',
            data: timePoints,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '(kWh)'
          }
        ],
        series: series
      }
      myChart.clear()
      option && myChart.setOption(option)
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart.resize()
      })
    },
    // 获取电量图标
    myChart2 (list) {
      const myChart = echarts.init(document.getElementById('usageecharts'))
      const timePoints = list[0]?.datalist.map((ele) => ele.timeReading)
      const series = list.map((ele) => {
        return {
          name: ele.name,
          data: ele.datalist.map((ele) => ele.valueReading),
          type: 'line',
          smooth: true
        }
      })
      const option = {
        grid: {
          top: '10%',
          bottom: '7%',
          left: '5%',
          right: '0%'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
        },
        xAxis: [
          {
            type: 'category',
            data: timePoints,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '(kWh)'
          }
        ],
        series: series
      }
      myChart.clear()
      option && myChart.setOption(option)
      window.addEventListener('resize', () => {
        myChart.resize()
      })
      // 根据当前容器的尺寸变化而让图表也跟着变化
      // const changeSize = elementResizeDetectorMaker()
      // const _this = this
      // changeSize.listenTo(chartDom, () => {
      //   // chartDom为之前获取到的容器名
      //   _this.$nextTick(() => {
      //     myChart.resize()
      //   })
      // })
    },
    filterNode (value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.option {
  padding-left: 10px;
}
.bigbox {
  height: 100%;
  padding: 10px;
  display: flex;
  .leftbox {
    width: 300px;
    padding: 15px;
    background-color: #fff;
    height: 100%;
    margin-right: 10px;
    .select {
      display: flex;
      align-items: center;
      .text {
        font-size: 14px;
        margin-right: 5px;
      }
      .span {
        display: inline-block;
        flex: 1;
      }
    }
    .title {
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
      button {
        width: 60px;
        height: 32px;
        border: none;
        border-radius: 3px;
        color: #fff;
        background-color: #1a90fe;
        margin-left: 10px;
      }
    }
  }
  .rightbox {
    width: calc(100% - 310px);
    height: 100%;
    display: flex;
    flex-direction: column;
    .righttopbox {
      display: flex;
      align-items: center;
      height: 80px;
      // line-height: 80px;
      padding: 0 20px;
      background-color: #fff;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      span {
        margin-left: 10px;
      }
      .button {
        width: 60px;
        height: 32px;
        background-color: #1a90fe;
        color: #fff;
        border-radius: 3px;
        border: none;
      }
      .chongzhi {
        width: 60px;
        height: 34px;
        border-radius: 3px;
        background-color: #fff;
        border: 1px solid #ccc;
        margin-right: 10px;
      }
    }
    .rightbodybox {
      // height: calc(100% - 90px);
      flex: 1;
      background-color: #fff;
      padding: 20px;
      .tages {
        height: 42px;
      }
      .title {
        display: flex;
        justify-content: space-between;
        img {
          vertical-align: middle;
        }
        span {
          margin-left: 10px;
          i:hover {
            color: #2194ff;
            cursor: pointer;
          }
          .button {
            width: 60px;
            height: 30px;
            background-color: #1a90fe;
            color: #fff;
            border-radius: 3px;
            border: none;
          }
        }
        i {
          width: 20px;
          height: 20px;
          margin-left: 10px;
        }
      }
      .tablebox {
        height: 87%;
        margin-top: 10px;
        .fartab {
          height: 95%;
          .fenye {
            text-align: right;
            margin-top: 10px;
          }
        }
        .keshihua {
          height: 100%;
          .fuherchart {
            height: 47%;
          }
          .dianliangechart {
            height: 47%;
          }
        }
      }
    }
  }
}
::v-deep .el-divider--vertical {
  height: 100%;
}
::v-deep .el-tag--light {
  padding: 0 10px;
  margin: 0 10px 10px 0;
}
</style>
